package com.example.mallsystem1104.service;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.mallsystem1104.constants.Constants;
import com.example.mallsystem1104.entity.Avatar;
import com.example.mallsystem1104.exception.ServiceException;
import com.example.mallsystem1104.mapper.AvatarMapper;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.List;
import java.util.UUID;

/**
 * @Author zy
 * @Date 2024/12/12 15:23
 * @packageName:com.example.mallsystem1104.service
 * @ClassName:AvatarService
 */
@Service
public class AvatarService extends ServiceImpl<AvatarMapper, Avatar> {
    @Resource
    private AvatarMapper avatarMapper;
    public String upload(MultipartFile file) {
        String url;
        //通过md5判断文件是否已经存在，防止在服务器中存储相同文件
        InputStream inputStream=null;
        try {
            inputStream=file.getInputStream();
        } catch (IOException e) {
            e.printStackTrace();
        }
        //md5加密
        String md5= SecureUtil.md5(inputStream);
        Avatar dbAvatar=avatarMapper.selectByMd5(md5);
        if(dbAvatar==null){
            String originFilename=file.getOriginalFilename();//获取文件的原始名
            String type=originFilename.substring(originFilename.lastIndexOf(".")+1);//文件后缀去除
            long size=file.getSize()/1024;//文件大小，单位为kb
            //如果文件不存在，则保存文件
            File folder=new File(Constants.avatarFolderPath);
            if (!folder.exists()){
                folder.mkdirs();
            }
            String folderPath=folder.getAbsolutePath()+"/";//文件存储文件夹的位置
            System.out.println(folderPath);

            //将文件保存为UUID的名字，通过uuid生成url
            String uuid= UUID.randomUUID().toString().replace("-","").toLowerCase();
            String finalFileName=uuid+"."+type;
            File targetFile=new File(folderPath+finalFileName);
            try {
                file.transferTo(targetFile);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
            url="/file/"+finalFileName;
            Avatar avatar=new Avatar(type,size,url,md5);
            avatarMapper.save(avatar);
            return url;

        }
        return dbAvatar.getUrl();
    }

    public void download(String fileName, HttpServletResponse response) {
        File file=new File(Constants.fileFolderPath+fileName);
        if(!file.exists()){
            throw new ServiceException(Constants.CODE_500,"文件不存在");
        }
        try {
            ServletOutputStream os=response.getOutputStream();
            response.addHeader("Content-Disposition","attachment;filename="+ URLEncoder.encode(fileName,"UTF-8"));
            response.setContentType("application/octet-stream");
            os.write(FileUtil.readBytes(file));
            os.flush();
            os.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public int delete(int id) {
        Avatar avatar=avatarMapper.selectById(id);
        int delete=avatarMapper.deleteById(id);
        if (delete==1){
            String filename= StrUtil.subAfter(avatar.getUrl(),"/",true);
            System.out.println(filename);
            File file=new File(Constants.avatarFolderPath+filename);
            System.out.println(file.getAbsolutePath());
            if (file.exists()){
                boolean delete1=file.delete();
                if (delete1){
                    System.out.println("删除成功");
                }
            }
        }
        return delete;

    }

    public List<Avatar> selectPage(int index, int pageSize) {
        return avatarMapper.selectAvatarPage(index,pageSize);
    }

    public int getTotal() {
        return avatarMapper.getTotal();
    }
}
